#!/bin/bash
# scanall.sh
# Scans for bad sectors on all devices on system, lists bad sectors on a file
#   and runs fsck for bad sectors when found.
# CAUTION: It is not well-tested, so please use carefully. Please report bugs if
#   found.

# Download, run `chmod +x /path/to/scanall.sh`, run `sudo ./scanall.sh`

if [ "$(id -u)" -ne 0 ]; then echo 'Please run as root.' >&2; exit 1; fi

device_lines=$(lsblk -o path,uuid,mountpoint -nl)
badsectorfile='/tmp/badsectors.txt'
echo "$device_lines" | while read line ; do
	# Find scannable FSs
	# Lines that have a UUID and not mounted
	device=$(echo "$line" | awk '{print $1}')
	uuid=$(echo "$line" | awk '{print $2}')
	mountpoint=$(echo "$line" | awk '{print $3}')
	if [ ! -z "$uuid" ] && [ -z "$mountpoint" ]; then
		echo "=== Scanning $device for bad sectors..."
		sudo badblocks -v "$device" > "$badsectorfile"
		if [ -s "$badsectorfile" ]; then
			echo "--- $device has bad sectors, running fsck..."
			sudo fsck -l "$badsectorfile" "$device"
			rm "$badsectorfile"
		else
			echo "--- $device does not have bad sectors, skipping fsck..."
		fi
	else
		if [ ! -z "$mountpoint" ]; then
			echo "=== Skipping $device because it's already mounted"
		else
			echo "=== Skipping $device"
		fi
	fi
done
rm "$badsectorfile"
